<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 日期限制配置管理
 *
 * @icon fa fa-calendar
 */
class DateRestriction extends Backend
{
    
    /**
     * DateRestriction模型对象
     * @var \app\admin\model\DateRestriction
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\DateRestriction;
    }

    /**
     * 获取日期限制配置
     * 用于前端JavaScript调用
     */
    public function getConfig()
    {
        $configKey = $this->request->get('key', '');
        
        $configs = [
            'workdays' => [
                'restrictionType' => 'workdays',
                'description' => '仅工作日（周一至周五）'
            ],
            'weekends' => [
                'restrictionType' => 'weekends', 
                'description' => '仅周末（周六、周日）'
            ],
            'custom_weekdays' => [
                'restrictionType' => 'custom',
                'allowedWeekdays' => [1, 2, 3], // 周一、周二、周三
                'description' => '自定义工作日'
            ],
            'specific_dates' => [
                'restrictionType' => 'specific',
                'allowedDates' => [
                    date('Y-m-d', strtotime('+1 day')),
                    date('Y-m-d', strtotime('+3 days')),
                    date('Y-m-d', strtotime('+7 days')),
                ],
                'description' => '指定可选日期'
            ],
            'disabled_dates' => [
                'restrictionType' => 'disabled',
                'disabledDates' => [
                    date('Y-m-d', strtotime('+2 days')),
                    date('Y-m-d', strtotime('+5 days')),
                ],
                'description' => '禁用特定日期'
            ],
            'holiday_restriction' => [
                'restrictionType' => 'disabled',
                'disabledDates' => $this->getHolidays(),
                'description' => '排除节假日'
            ]
        ];

        if ($configKey && isset($configs[$configKey])) {
            $this->success('获取成功', null, $configs[$configKey]);
        } else {
            $this->success('获取成功', null, $configs);
        }
    }

    /**
     * 获取节假日列表
     * 这里可以根据实际需求从数据库或API获取
     */
    private function getHolidays()
    {
        // 示例：2024年部分节假日
        return [
            '2024-01-01', // 元旦
            '2024-02-10', '2024-02-11', '2024-02-12', '2024-02-13', '2024-02-14', '2024-02-15', '2024-02-16', '2024-02-17', // 春节
            '2024-04-04', '2024-04-05', '2024-04-06', // 清明节
            '2024-05-01', '2024-05-02', '2024-05-03', // 劳动节
            '2024-06-10', // 端午节
            '2024-09-15', '2024-09-16', '2024-09-17', // 中秋节
            '2024-10-01', '2024-10-02', '2024-10-03', '2024-10-04', '2024-10-05', '2024-10-06', '2024-10-07', // 国庆节
        ];
    }

    /**
     * 动态生成日期限制配置
     */
    public function generateConfig()
    {
        $type = $this->request->post('type', '');
        $params = $this->request->post('params', []);
        
        $config = [];
        
        switch ($type) {
            case 'workdays':
                $config = [
                    'restrictionType' => 'workdays'
                ];
                break;
                
            case 'weekends':
                $config = [
                    'restrictionType' => 'weekends'
                ];
                break;
                
            case 'custom':
                $config = [
                    'restrictionType' => 'custom',
                    'allowedWeekdays' => isset($params['weekdays']) ? $params['weekdays'] : []
                ];
                break;
                
            case 'specific':
                $config = [
                    'restrictionType' => 'specific',
                    'allowedDates' => isset($params['dates']) ? $params['dates'] : []
                ];
                break;
                
            case 'disabled':
                $config = [
                    'restrictionType' => 'disabled',
                    'disabledDates' => isset($params['dates']) ? $params['dates'] : []
                ];
                break;
                
            default:
                $this->error('不支持的限制类型');
        }
        
        $this->success('配置生成成功', null, $config);
    }

    /**
     * 获取快捷日期按钮配置
     */
    public function getQuickDates()
    {
        $type = $this->request->get('type', 'workdays');
        $count = $this->request->get('count', 5);
        
        $quickDates = [];
        $currentDate = new \DateTime();
        $addedCount = 0;
        
        while ($addedCount < $count) {
            $currentDate->add(new \DateInterval('P1D'));
            $dateString = $currentDate->format('Y-m-d');
            $dayOfWeek = $currentDate->format('w'); // 0=周日, 1=周一, ..., 6=周六
            
            $shouldAdd = false;
            
            switch ($type) {
                case 'workdays':
                    $shouldAdd = ($dayOfWeek >= 1 && $dayOfWeek <= 5);
                    break;
                case 'weekends':
                    $shouldAdd = ($dayOfWeek == 0 || $dayOfWeek == 6);
                    break;
                default:
                    $shouldAdd = true;
            }
            
            if ($shouldAdd) {
                $quickDates[] = [
                    'date' => $dateString,
                    'label' => $currentDate->format('m月d日') . ' (' . $this->getDayName($dayOfWeek) . ')',
                    'dayOfWeek' => $dayOfWeek
                ];
                $addedCount++;
            }
        }
        
        $this->success('获取成功', null, $quickDates);
    }
    
    /**
     * 获取星期名称
     */
    private function getDayName($dayOfWeek)
    {
        $days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return $days[$dayOfWeek];
    }

    /**
     * 验证日期是否符合限制条件
     */
    public function validateDate()
    {
        $date = $this->request->post('date', '');
        $configKey = $this->request->post('config_key', '');
        
        if (empty($date)) {
            $this->error('日期不能为空');
        }
        
        // 获取配置
        $configs = $this->getConfig();
        if (!isset($configs[$configKey])) {
            $this->error('配置不存在');
        }
        
        $config = $configs[$configKey];
        $dateObj = new \DateTime($date);
        $dayOfWeek = $dateObj->format('w');
        
        $isValid = true;
        $message = '日期有效';
        
        switch ($config['restrictionType']) {
            case 'workdays':
                $isValid = ($dayOfWeek >= 1 && $dayOfWeek <= 5);
                if (!$isValid) $message = '只能选择工作日（周一至周五）';
                break;
                
            case 'weekends':
                $isValid = ($dayOfWeek == 0 || $dayOfWeek == 6);
                if (!$isValid) $message = '只能选择周末（周六、周日）';
                break;
                
            case 'custom':
                if (isset($config['allowedWeekdays'])) {
                    $isValid = in_array($dayOfWeek, $config['allowedWeekdays']);
                    if (!$isValid) $message = '该日期不在允许的星期范围内';
                }
                break;
                
            case 'specific':
                if (isset($config['allowedDates'])) {
                    $isValid = in_array($date, $config['allowedDates']);
                    if (!$isValid) $message = '该日期不在允许的日期列表中';
                }
                break;
                
            case 'disabled':
                if (isset($config['disabledDates'])) {
                    $isValid = !in_array($date, $config['disabledDates']);
                    if (!$isValid) $message = '该日期已被禁用';
                }
                break;
        }
        
        if ($isValid) {
            $this->success($message, null, ['valid' => true, 'date' => $date]);
        } else {
            $this->error($message, null, ['valid' => false, 'date' => $date]);
        }
    }
}